package com.tyylab.message.event.listener.service.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.tyylab.message.core.intf.IConditionalSubscribe;
import com.tyylab.message.core.model.TransMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE)
public class MessageSubscribe implements IConditionalSubscribe {

    @Autowired
    ApplicationContext context;
    Map<String, Class> classMap = Maps.newConcurrentMap();
    @Override
    public boolean isSubscribe(String clz) {
        if (StringUtils.isNotBlank(clz)) {
            return true;
        }
        else{
            return false;
        }
    }

    @EventListener(ContextRefreshedEvent.class)
    public void start(ContextRefreshedEvent e){
        log.info("加载完成..");
    }

    //@SneakyThrows
    @Override
    public void onMesssage(TransMessage transMessage) {
        MDC.put("requestId",transMessage.getId());
        log.info("process message : " + JSON.toJSONString(transMessage));
        try{
            Class clz = null;
            if (classMap.containsKey(transMessage.getClz())){
                clz = classMap.get(transMessage.getClz());

            }
            else {
                try {
                    clz = Class.forName(transMessage.getClz());
                    classMap.put(transMessage.getClz(), clz);
                }
                catch (Exception e){
                    log.error(e.getMessage()+ ",Message:" + JSON.toJSONString(transMessage),e);
                    log.info("finish process message : " +JSON.toJSONString(transMessage));
                    return;
                }
            }
            Object event = JSONObject.toJavaObject(transMessage.getMessage(), clz);
            context.publishEvent(event);
        }
        catch (Exception e){
            log.error(e.getMessage()+ ",Message:" + JSON.toJSONString(transMessage),e);
        }
        log.info("finish process message : " +JSON.toJSONString(transMessage));
    }
}
